package com.datamation.swadeshi.view;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SearchView.OnQueryTextListener;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.FreeIssueAdapter;
import com.datamation.swadeshi.adapter.InvDetAdapter;
import com.datamation.swadeshi.adapter.OrderDetailsAdapter;
import com.datamation.swadeshi.adapter.ProductAdapter;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.AddressAyncTask;
import com.datamation.swadeshi.control.DefaultTaskListener;
import com.datamation.swadeshi.control.FreeIssue;
import com.datamation.swadeshi.control.ReferenceNum;
import com.datamation.swadeshi.control.Toast;
import com.datamation.swadeshi.control.data.DebtorDS;
import com.datamation.swadeshi.control.data.InvDetDS;
import com.datamation.swadeshi.control.data.InvHedDS;
import com.datamation.swadeshi.control.data.ItemPriDS;
import com.datamation.swadeshi.control.data.ItemsDS;
import com.datamation.swadeshi.control.data.OrdDetDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.control.data.SalRepDS;
import com.datamation.swadeshi.control.data.SharedPreferencesClass;
import com.datamation.swadeshi.model.FreeItemDetails;
import com.datamation.swadeshi.model.InvDet;
import com.datamation.swadeshi.model.InvHed;
import com.datamation.swadeshi.model.ItemFreeIssue;
import com.datamation.swadeshi.model.Items;
import com.datamation.swadeshi.model.OrdDet;
import com.datamation.swadeshi.model.OrdHed;

public class FragmentSalesManagementVanSalesOrderDetails extends Fragment implements OnClickListener, DefaultTaskListener{

	View view;
	Button itemSearch,bAdd,bFreeIssue;
	EditText et_item,et_unit,et_price,et_cases,et_pieces,et_dis_amt,et_dis_per;
	
	//calculation variables
	int totPieces =0;
	double values=0.00;
	double totalDiscount=0.00;
	
	TextView tv_value,tv_total_discount_amt;
	Items selectedItem=null;
	int seqno=0, index_id=0;
	Toast  toast;
	public static SharedPreferences localSP;
	public static final String SETTINGS = "SETTINGS";
	
	ListView lv_order_det;
	ArrayList<InvDet> orderList;
	OrdDetDS detDS = null;
	ReferenceNum referenceNum;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		view = inflater.inflate(R.layout.sales_management_van_sales_details, container, false);
		
		toast = new Toast();
		
		seqno=0; 
		totPieces =0;
		
		localSP = getActivity().getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		//button
		itemSearch= (Button) view.findViewById(R.id.btn_item_search);
		bAdd=(Button) view.findViewById(R.id.btn_add);
		bFreeIssue=(Button) view.findViewById(R.id.btn_free);
		
		//editText 
		et_item=(EditText) view.findViewById(R.id.et_item);
		et_unit=(EditText) view.findViewById(R.id.et_unit);
		et_price=(EditText) view.findViewById(R.id.et_price);
		
		et_cases=(EditText) view.findViewById(R.id.et_cases);
		et_pieces=(EditText) view.findViewById(R.id.et_pieces);
		
		et_dis_amt=(EditText) view.findViewById(R.id.et_dis_amt);
		et_dis_per=(EditText) view.findViewById(R.id.et_dis_per);
		
		//TextView
		tv_value=(TextView) view.findViewById(R.id.tv_value);
		tv_total_discount_amt=(TextView) view.findViewById(R.id.tv_total_discount_amt);
		
		
		
		//button action
		itemSearch.setOnClickListener(this);
		bAdd.setOnClickListener(this);
		bFreeIssue.setOnClickListener(this);
		
		MainActivity activity =(MainActivity) getActivity();
		
		referenceNum=new  ReferenceNum(getActivity());
	
		InvHedDS invHedDS =new InvHedDS(getActivity());
		ArrayList<InvHed> getInvHed = invHedDS.getAllActiveInvhed(referenceNum.getCurrentRefNo(getResources().getString(R.string.VanNumVal)));
		
		if(!getInvHed.isEmpty()){
			
			for (InvHed invHed : getInvHed) {
								
				activity.selectedInvHed=invHed;
				
				if(activity.selectedDebtor==null){
					DebtorDS debtorDS =new DebtorDS(getActivity());
					activity.selectedDebtor=debtorDS.getSelectedCustomerByCode(invHed.getFINVHED_DEB_CODE());
				}
			}
			
		}
		
		//set title 
		setTitle("Order Details - Van");
		
		try{
		
			if(activity.selectedDebtor == null){
				//Toast.makeText(getActivity(),"Please select a customer", Toast.LENGTH_SHORT).show();
				toast.createToastMessage("Please select a customer", getActivity());
				getActivity().getActionBar().setSelectedNavigationItem(0);
			}else{
				if(activity.selectedInvHed == null)
				{
					getActivity().getActionBar().setSelectedNavigationItem(1);
				}
			}
		}catch (NumberFormatException e){
			getActivity().getActionBar().setSelectedNavigationItem(0);
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
		
		
		//address
		try {
			
			if(activity.selectedInvHed.getFINVHED_ADDRESS() == null){
				
				 new AddressAyncTask(getActivity(),this).execute();
				 
			}else{
				
				Log.v("GPS address", activity.selectedInvHed.getFINVHED_ADDRESS().toString());
				
			}
		}catch (Exception e){
			Log.v("Exception", e.toString());
		}

		//Set data in the ListView.	
		fatchData();
		
		//cases
		et_cases.addTextChangedListener(new TextWatcher(){
		    public void afterTextChanged(Editable s) {
		       
		    	casesCalc();

		    	if(totPieces>0){
		    		et_dis_amt.setEnabled(true);
		    		et_dis_per.setEnabled(true);
		    	}
		    	
		    }
		    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
		    public void onTextChanged(CharSequence s, int start, int before, int count){}
		}); 
		
		//Pieces
		et_pieces.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
				
				piecesCalc();
				
				if(totPieces>0){
		    		et_dis_amt.setEnabled(true);
		    		et_dis_per.setEnabled(true);
		    	}
				
		    }
		    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
		    public void onTextChanged(CharSequence s, int start, int before, int count){}
		}); 
		
		
		//** Discount values **//
		//discount value 
		et_dis_amt.addTextChangedListener(new TextWatcher(){
		    public void afterTextChanged(Editable s) {
		       
		    	if(totPieces>0){
		    		//et_dis_amt.setEnabled(true);
		    		discountAmountCalc();
		    	}

		    }
		    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
		    public void onTextChanged(CharSequence s, int start, int before, int count){}
		}); 
		
		//discount % 
		et_dis_per.addTextChangedListener(new TextWatcher(){
		    public void afterTextChanged(Editable s) {
			   
		    	if(totPieces>0){
		    		discountpercentageCalc();
		    	}
		    	
		    }
		    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
		    public void onTextChanged(CharSequence s, int start, int before, int count){}
		});
		
		lv_order_det.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
			
				InvDet invDet = orderList.get(position);
				deleteOrderDialog(getActivity(), "Order Details (SA)",invDet.getFINVDET_ID());
				
				return false;
			}
		});
		
		lv_order_det.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view2,int position, long id) {
				
				InvDet invDet = orderList.get(position);
				if(!invDet.getFINVDET_TYPE().equals("FI")){
					selectedItem=new Items();
					selectedItem.setFITEM_ITEM_CODE(invDet.getFINVDET_ITEM_CODE());
					
					index_id= Integer.parseInt(invDet.getFINVDET_ID());
					
					bAdd.setText("Edit");
					
					ItemsDS ds =new ItemsDS(getActivity());
					et_item.setText(ds.getItemNameByCode(invDet.getFINVDET_ITEM_CODE()));
					et_unit.setText(ds.getUnitByCode(invDet.getFINVDET_ITEM_CODE()));
					et_price.setText(invDet.getFINVDET_B_SELL_PRICE());
					et_cases.setText(invDet.getFINVDET_CASE_QTY());
					et_pieces.setText(invDet.getFINVDET_PICE_QTY());
					et_dis_amt.setText(invDet.getFINVDET_DIS_VAL_AMT());
					et_dis_per.setText(invDet.getFINVDET_DIS_PER());
				
				}else if(invDet.getFINVDET_TYPE().equals("FI")){
				
					clearTextFields();
					
				}
			}
		});
		
		
		//Highlight text when edittext
		//Cases
		et_cases.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				//et_cases.setSelectAllOnFocus(true);
			}
		});
		
		//Pieces
		et_pieces.setOnFocusChangeListener(new OnFocusChangeListener()
		{
			@Override
			public void onFocusChange(View v, boolean hasFocus)
			{
				
				
					//et_pieces.setSelectAllOnFocus(true);
				
			}
		});
		
		//dis amount
		et_dis_amt.setOnFocusChangeListener(new OnFocusChangeListener()
		{
			@Override
			public void onFocusChange(View v, boolean hasFocus)
			{
				
				
					//et_dis_amt.setSelectAllOnFocus(true);
			
			}
		});
		
		//dis %
		et_dis_per.setOnFocusChangeListener(new OnFocusChangeListener()
		{
			@Override
			public void onFocusChange(View v, boolean hasFocus)
			{
			
					//et_dis_per.setSelectAllOnFocus(true);
				
			}
		});
		return view;
	}

	
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_item_search:
	
			clearTextFields();
			prodcutDetailsDialogbox();
			
			break;
		case R.id.btn_free:{
			try {	
				
					bFreeIssue.setClickable(false);
					
					ReferenceNum referenceNum =new  ReferenceNum(getActivity());
					
					ArrayList<InvDet> Inv= new InvDetDS(getActivity()).getSAForFreeIssueCalc(referenceNum.getCurrentRefNo(getResources().getString(R.string.VanNumVal)));
					
					new OrdDetDS(getActivity()).restFreeIssueData(referenceNum.getCurrentRefNo(getResources().getString(R.string.VanNumVal)));
					
					fatchData();
					
					FreeIssue issue =new FreeIssue(getActivity()); 
					ArrayList<FreeItemDetails> list =issue.getFreeItemsByVanSalesItem(Inv);
					
					for (FreeItemDetails freeItemDetails : list) {
						
						//android.widget.Toast.makeText(getActivity(),freeItemDetails.getFreeIssueSelectedItem()+" "+ freeItemDetails.getRefno()+"  "+freeItemDetails.getFreeQty(), android.widget.Toast.LENGTH_SHORT).show();
						
						freeIssueDialogBox(freeItemDetails);
						
					}
				
			}catch (Exception e){
				Log.v("Exception", e.toString());
			}
		}
			break;
		case R.id.btn_add:{
		
			if(!et_item.getText().toString().equals("")){	
				
				if(values >= 0.0 && totPieces >0 ){
					//det
					InvDet invDet=new InvDet();
					InvDetDS invDetDS=new InvDetDS(getActivity());
					ArrayList< InvDet> ordList=new ArrayList<InvDet>();
					
					MainActivity activity =(MainActivity) getActivity();
					//hed
					InvHedDS invHedDS =new  InvHedDS(getActivity());
					SalRepDS repDS=new SalRepDS(getActivity());
					ArrayList<InvHed> invHedList=new ArrayList<InvHed>();
					
					ItemPriDS priDS = new ItemPriDS(getActivity());
					
					
					//head
					invHedList.add(activity.selectedInvHed);
				
					if(invHedDS.createOrUpdateInvHed(invHedList)>0){
						//details 
						seqno++;
						
						invDet.setFINVDET_ID(index_id+"");
						invDet.setFINVDET_AMT(String.format("%,.2f",values));
						invDet.setFINVDET_BAL_QTY(totPieces+"");
						invDet.setFINVDET_B_AMT(String.format("%,.2f",values));
						invDet.setFINVDET_B_DIS_AMT(String.format("%,.2f",(Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) * Double.parseDouble(et_dis_per.getText().toString())/100));
						invDet.setFINVDET_BP_DIS_AMT(String.format("%,.2f",(Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) * Double.parseDouble(et_dis_per.getText().toString())/100));
						invDet.setFINVDET_B_SELL_PRICE(et_price.getText().toString());
						invDet.setFINVDET_BT_TAX_AMT("0");
						invDet.setFINVDET_BT_SELL_PRICE("0");
						invDet.setFINVDET_CASE((new Double(totPieces/Integer.parseInt(et_unit.getText().toString()))).intValue()+"");
						invDet.setFINVDET_CASE_QTY((new Double(totPieces/Integer.parseInt(et_unit.getText().toString()))).intValue()+"");
						invDet.setFINVDET_DIS_AMT(String.format("%,.2f",(Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) * Double.parseDouble(et_dis_per.getText().toString())/100));
						invDet.setFINVDET_DIS_PER(et_dis_per.getText().toString());
						invDet.setFINVDET_FREE_QTY("0");
						invDet.setFINVDET_ITEM_CODE(selectedItem.getFITEM_ITEM_CODE());
						invDet.setFINVDET_P_DIS_AMT(String.format("%,.2f",(Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) * Double.parseDouble(et_dis_per.getText().toString())/100));
						invDet.setFINVDET_PRIL_CODE(priDS.getPrilCodeByItemCode(selectedItem.getFITEM_ITEM_CODE()));
						invDet.setFINVDET_QTY(totPieces+"");
						invDet.setFINVDET_DIS_VAL_AMT(et_dis_amt.getText().toString());
						invDet.setFINVDET_PICE_QTY(totPieces % Integer.parseInt(et_unit.getText().toString())+"");
						invDet.setFINVDET_REA_CODE("");
						invDet.setFINVDET_TYPE("SA");
						invDet.setFINVDET_RECORD_ID("");
						invDet.setFINVDET_REFNO(activity.selectedInvHed.getFINVHED_REFNO());
						invDet.setFINVDET_SELL_PRICE(et_price.getText().toString());
						invDet.setFINVDET_SEQNO(seqno+"");
						invDet.setFINVDET_TAX_AMT("0.00");
						invDet.setFINVDET_TAX_COM_CODE("");
						invDet.setFINVDET_TIMESTAMP_COLUMN("");
						invDet.setFINVDET_T_SELL_PRICE("0");
						
						DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						Date date = new Date();
						//currnentDate.setText(dateFormat.format(date));
						invDet.setFINVDET_TXN_DATE(dateFormat.format(date));
						invDet.setFINVDET_TXN_TYPE("22");
						invDet.setFINVDET_IS_ACTIVE("1");
						
						ordList.add(invDet);
						
						if(invDetDS.createOrUpdateInvDet(ordList) > 0){
							clearTextFields();
							toast.createToastMessage("Added successfully", getActivity());
							fatchData();
						}
				}		
					
			}
		}	
	}
			break;
		default:
			break;
		}
	}
	
	private void deleteOrderDialog(final Context context,String title, final String recordId){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to delete this entry?");
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
							
								int count =new InvDetDS(context).deleteInvDetByID(recordId);			
								if(count >0){
									//android.widget.Toast.makeText(context, "Deleted successfully",android.widget.Toast.LENGTH_LONG).show();
									toast.createToastMessage("Deleted successfully", getActivity());
									fatchData();
									clearTextFields();
								}
							}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
								
								
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	public void fatchData(){
		try {
			MainActivity activity =(MainActivity) getActivity();
			lv_order_det = (ListView) view.findViewById(R.id.lv_order_det);
			lv_order_det.clearTextFilter();
			InvDetDS detDS = new InvDetDS(getActivity());
			orderList = detDS.getAllInvDet(activity.selectedInvHed.getFINVHED_REFNO());
			lv_order_det.setAdapter(new InvDetAdapter(getActivity(), orderList));
		}catch (NullPointerException e){
			Log.v("SA Error", e.toString());
		}
	}
	
//---------free issue dialog box-------------
	@SuppressWarnings("unused")
	private boolean freeIssueDialogBox(final FreeItemDetails itemDetails){
		
		final ArrayList<ItemFreeIssue> itemFreeIssues;
		
		// get prompts.xml view
		LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

		View promptView = layoutInflater.inflate(R.layout.free_issues_items_dialog, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		
		alertDialogBuilder.setTitle("Free Issue Schemas");
				//+ "- "+ new ItemsDS(getActivity()).getItemNameByCode(itemDetails.getFreeIssueSelectedItem()) );
		
		alertDialogBuilder.setView(promptView);
		
		final ListView listView=(ListView) promptView.findViewById(R.id.lv_free_issue);
		final TextView itemName=(TextView) promptView.findViewById(R.id.tv_free_issue_item_name);
		final TextView freeQty= (TextView) promptView.findViewById(R.id.tv_free_qty);
		
		freeQty.setText("Free Qty you have : "+itemDetails.getFreeQty());
		itemName.setText("Item Name: "+new ItemsDS(getActivity()).getItemNameByCode(itemDetails.getFreeIssueSelectedItem()));
		
		final ItemsDS itemsDS =new ItemsDS(getActivity());
		itemFreeIssues=itemsDS.getAllFreeItemNameByRefno(itemDetails.getRefno());
		listView.setAdapter(new FreeIssueAdapter(getActivity(), itemFreeIssues));
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			int avaliableQty=0;
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view2,final int position, long id) {
				
			if(itemDetails.getFreeQty()>0){
				
				ItemFreeIssue freeIssue = itemFreeIssues.get(position);
				LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

				View promptView = layoutInflater.inflate(R.layout.set_free_issue_dialog, null);
				
				final TextView leftQty= (TextView) promptView.findViewById(R.id.tv_free_item_left_qty);
				final EditText enteredQty=(EditText) promptView.findViewById(R.id.et_free_qty);
				
				leftQty.setText("Free Items Left = "+itemDetails.getFreeQty());
				
				enteredQty.addTextChangedListener(new TextWatcher(){
				    public void afterTextChanged(Editable s) {
				       
				    	if(enteredQty.getText().toString().equals("")){
				    		
				    		leftQty.setText("Free Items Left = "+itemDetails.getFreeQty());
				    		
				    	}else{
				    		avaliableQty=itemDetails.getFreeQty()-Integer.parseInt(enteredQty.getText().toString());
				    		
				    		if(avaliableQty<0)
				    		{
				    			enteredQty.setText("");
				    			leftQty.setText("Free Items Left = "+itemDetails.getFreeQty());
				    			//error meassage
				    			android.widget.Toast.makeText(getActivity(),"You don't have enough sufficient quantity to order", android.widget.Toast.LENGTH_SHORT).show();
				    		}else{
				    			leftQty.setText("Free Items Left = "+avaliableQty);
				    		}
				    		
				    	}
				    	
				    }
				    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
				    public void onTextChanged(CharSequence s, int start, int before, int count){}
				}); 
				
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
				alertDialogBuilder.setTitle(freeIssue.getItems().getFITEM_ITEM_NAME());
				alertDialogBuilder.setView(promptView);

				
				
				alertDialogBuilder
						.setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
									
										itemDetails.setFreeQty(avaliableQty);
										freeQty.setText("Free Qty you have : "+itemDetails.getFreeQty());
										
										itemFreeIssues.get(position).setAlloc(enteredQty.getText().toString());
										listView.clearTextFilter();
										listView.setAdapter(new FreeIssueAdapter(getActivity(), itemFreeIssues));
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,	int id) {
										dialog.cancel();
										
										
									}
								});
				
				AlertDialog alertD = alertDialogBuilder.create();

				alertD.show();
			}else{
				//toast.createToastErrorMessage("You don't have enough sufficient quantity to order", getActivity());
				android.widget.Toast.makeText(getActivity(),"You don't have enough sufficient quantity to order", android.widget.Toast.LENGTH_SHORT).show();
			}
				
			}
		});
		
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								bFreeIssue.setClickable(true);
								
								for (ItemFreeIssue itemFreeIssue : itemFreeIssues) {
									
									if(Integer.parseInt(itemFreeIssue.getAlloc())>0){
										
										seqno++;
										InvDet invDet=new InvDet();
										InvDetDS invDetDS=new InvDetDS(getActivity());
										ArrayList< InvDet> ordList=new ArrayList<InvDet>();
										ItemPriDS priDS = new ItemPriDS(getActivity());
										MainActivity activity =(MainActivity) getActivity();
										
										invDet.setFINVDET_ID("0");
										invDet.setFINVDET_AMT("0.00");
										invDet.setFINVDET_BAL_QTY(itemFreeIssue.getAlloc());
										invDet.setFINVDET_B_AMT("0.00");
										invDet.setFINVDET_B_DIS_AMT("0.00");
										invDet.setFINVDET_BP_DIS_AMT("0.00");
										
										double unitPrice= Double.parseDouble(priDS.getProductPriceByCode(itemFreeIssue.getItems().getFITEM_ITEM_CODE()))/Double.parseDouble(itemFreeIssue.getItems().getFITEM_NOU_CASE());
										
										invDet.setFINVDET_B_SELL_PRICE(unitPrice+"");
										invDet.setFINVDET_BT_TAX_AMT("0");
										invDet.setFINVDET_BT_SELL_PRICE("0");
										invDet.setFINVDET_CASE((new Double(Integer.parseInt(itemFreeIssue.getAlloc())/Integer.parseInt(itemFreeIssue.getItems().getFITEM_NOU_CASE()))).intValue()+"");
										invDet.setFINVDET_CASE_QTY((new Double(Integer.parseInt(itemFreeIssue.getAlloc())/Integer.parseInt(itemFreeIssue.getItems().getFITEM_NOU_CASE()))).intValue()+"");
										invDet.setFINVDET_DIS_AMT("0.00");
										invDet.setFINVDET_DIS_PER("0.00");
										invDet.setFINVDET_FREE_QTY("0");
										invDet.setFINVDET_ITEM_CODE(itemFreeIssue.getItems().getFITEM_ITEM_CODE());
										invDet.setFINVDET_P_DIS_AMT("0.00");
										invDet.setFINVDET_PRIL_CODE(priDS.getPrilCodeByItemCode(itemFreeIssue.getItems().getFITEM_ITEM_CODE()));
										invDet.setFINVDET_QTY(itemFreeIssue.getAlloc());
										invDet.setFINVDET_DIS_VAL_AMT("0.00");
										invDet.setFINVDET_PICE_QTY(Integer.parseInt(itemFreeIssue.getAlloc()) % Integer.parseInt(itemFreeIssue.getItems().getFITEM_NOU_CASE())+"");
										invDet.setFINVDET_REA_CODE("");
										invDet.setFINVDET_TYPE("FI");
										invDet.setFINVDET_RECORD_ID("");
										invDet.setFINVDET_REFNO(activity.selectedOrdHed.getFORDHED_REFNO());
										invDet.setFINVDET_SELL_PRICE(unitPrice+"");
										invDet.setFINVDET_SEQNO(seqno+"");
										invDet.setFINVDET_TAX_AMT("");
										invDet.setFINVDET_TAX_COM_CODE("");
										invDet.setFINVDET_TIMESTAMP_COLUMN("");
										invDet.setFINVDET_T_SELL_PRICE("0");
										
										DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
										Date date = new Date();
										//currnentDate.setText(dateFormat.format(date));
										invDet.setFINVDET_TXN_DATE(dateFormat.format(date));
										invDet.setFINVDET_TXN_TYPE("27");
										invDet.setFINVDET_IS_ACTIVE("1");
										
										ordList.add(invDet);
										
										if(invDetDS.createOrUpdateInvDet(ordList) > 0){
											clearTextFields();
											toast.createToastMessage("Added successfully", getActivity());
											fatchData();
										}
									}
									
								}
								
							}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
								
								bFreeIssue.setClickable(true);
								
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	   return true;
	}
	
		
	
//	@SuppressWarnings("unused")
//	private void setFreeIssueQtyDialog(ItemFreeIssue freeIssue, FreeItemDetails itemDetails){
//	
//		LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
//
//		View promptView = layoutInflater.inflate(R.layout.set_free_issue_dialog, null);
//		
//		final TextView leftQty= (TextView) promptView.findViewById(R.id.tv_free_item_left_qty);
//		final EditText enteredQty=(EditText) promptView.findViewById(R.id.et_free_qty);
//		
//		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
//		alertDialogBuilder.setTitle(freeIssue.getItems().getFITEM_ITEM_NAME());
//		alertDialogBuilder.setView(promptView);
//
//		leftQty.setText("Free Items Left = "+itemDetails.getFreeQty());
//		
//		alertDialogBuilder
//				.setCancelable(false)
//				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//							public void onClick(DialogInterface dialog, int id) {
//							
//								
//							}
//						})
//				.setNegativeButton("Cancel",
//						new DialogInterface.OnClickListener() {
//							public void onClick(DialogInterface dialog,	int id) {
//								dialog.cancel();
//								
//								
//							}
//						});
//		
//		AlertDialog alertD = alertDialogBuilder.create();
//
//		alertD.show();
//	}
	
/*
 * -----------------------------------------calcuations----------------------------------
 */
// -- pieces --
private void piecesCalc(){
	    if(!(et_unit.length() == 0)){	
			
	    	if(!(et_pieces.length() == 0)){
		
	    			if(et_cases.length() == 0){
		    			et_cases.setText("0");
		    		}
		    		
	    			totPieces=(Integer.parseInt(et_cases.getText().toString()) * Integer.parseInt(et_unit.getText().toString())) +  Integer.parseInt(et_pieces.getText().toString());
		    		
	    			Log.v("Total Pieces (Pieces)", totPieces+"");
	    		}else{
	    			
	    			if(et_cases.length() == 0){
		    			et_cases.setText("0");
		    		}
		    		
	    			totPieces=(Integer.parseInt(et_cases.getText().toString()) * Integer.parseInt(et_unit.getText().toString())) + 0;
		    		
	    			Log.v("Total Pieces (Pieces)", totPieces+"");
	    		}
	    	
	    		
	    		values= (Double.parseDouble(et_price.getText().toString())* ((double) totPieces)) - totalDiscount;
	    		discountAmountCalc();
	    		setValues(String.format("%,.2f", values),String.format("%,.2f",totalDiscount));
	    	}	
	}

	// ---cases---
	private void casesCalc(){
    	if(!(et_unit.length() == 0)){	
		    
    		if(!(et_cases.length() == 0)){
    		
    			if(et_pieces.length() == 0){
    				et_pieces.setText("0");
    			}
    		
    			totPieces=(Integer.parseInt(et_cases.getText().toString()) * Integer.parseInt(et_unit.getText().toString())) +  Integer.parseInt(et_pieces.getText().toString());
    		
    			Log.v("Total Pieces (cases)", totPieces+"");
    		}else{
	    		
    			if(et_pieces.length() == 0){
		    		et_pieces.setText("0");
	    		}
    		
    			totPieces=( 0 * Integer.parseInt(et_unit.getText().toString())) +  Integer.parseInt(et_pieces.getText().toString());
    		
    			Log.v("Total Pieces (cases)", totPieces+"");
    		}
    		
    		
    		values= (Double.parseDouble(et_price.getText().toString())* ((double) totPieces)) - totalDiscount; 
    		discountAmountCalc();
    		setValues(String.format("%,.2f",values),String.format("%,.2f",totalDiscount));
    	}
	}
//---------------------------------------------discount calcuations--------------------------------------
	// ---- discount amount calc ----
private void discountAmountCalc() {
		// TODO Auto-generated method stub
    if(!(et_unit.length() == 0)){	

    	//if(values > 0.00){
	    		
    		if(!(et_dis_amt.length() == 0)){
		    		
			    	if(et_dis_per.length() == 0){
			    		et_dis_per.setText("0.00");
			    	}
			    
			    	//totalDiscount= ((Double.parseDouble(et_dis_amt.getText().toString())) + ((Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) - (Double.parseDouble(et_dis_amt.getText().toString()))) * Double.parseDouble(et_dis_per.getText().toString())/100);
			    	totalDiscount= ((Double.parseDouble(et_dis_amt.getText().toString())) + ((Double.parseDouble(et_price.getText().toString()) * ((double) totPieces))) * Double.parseDouble(et_dis_per.getText().toString())/100);		
			    	Log.v("Total Pieces (value 1)", totalDiscount+"");
	    	}else{
			    		
			    if(et_dis_per.length() == 0){
			    	et_dis_per.setText("0.00");
				}
			    
			    
			    	totalDiscount= (0.00 + ((Double.parseDouble(et_price.getText().toString()) * ((double) totPieces))) * Double.parseDouble(et_dis_per.getText().toString())/100);
			    
			    	Log.v("discount (value 2)", totalDiscount+"");
	    	}
	    		
	    		
    		values= (Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) - totalDiscount; 
    				
	    	if((Double.parseDouble(et_price.getText().toString())* ((double) totPieces)) < totalDiscount){
	    		//Toast.makeText(getActivity(),"Maximum Discount Amount Exceed...", Toast.LENGTH_SHORT).show();
	    		toast.createToastErrorMessage("Maximum Discount Amount Exceed...", getActivity());
	    		et_dis_amt.setText("0");
	    		et_dis_per.setText("0.00");
    			totalDiscount=0.00;
	    		values=0.00;
	    		casesCalc();
	    		discountAmountCalc();
    		
	    	}else{
	    		setValues(String.format("%,.2f",values),String.format("%,.2f",totalDiscount));
	    	}	
//    	}else{
//    		Log.v("### Testing ###", "DISCOUNT AMT");
//    	}
			
   	}	
}

//--- discount percentage calc ---
private void discountpercentageCalc() {
		// TODO Auto-generated method stub
    if(!(et_unit.length() == 0)){	
    
    	//if(values > 0.00){
	   		if(!(et_dis_per.length() == 0)){
	   		
	   			if(et_dis_amt.length() == 0){
	    				et_dis_amt.setText("0");
	   				}
			
	   			if(et_dis_per.getText().toString().equals(".")){
	   					
	   					et_dis_per.setText("0.");
	   					//Set cursor position to end of the text after updating the text of EditText 
	   					int position = et_dis_per.length();
	   					Editable etext = et_dis_per.getText();
	   					Selection.setSelection(etext, position);
	   					
	   			}
	   			//totalDiscount= ((Double.parseDouble(et_dis_amt.getText().toString())) + ((Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) - (Double.parseDouble(et_dis_amt.getText().toString()))) * Double.parseDouble(et_dis_per.getText().toString())/100);
	   			totalDiscount= ((Double.parseDouble(et_dis_amt.getText().toString())) + ((Double.parseDouble(et_price.getText().toString()) * ((double) totPieces))) * Double.parseDouble(et_dis_per.getText().toString())/100);
			Log.v("Total  (Discount % 1)", totalDiscount+"");
			
		}else{
			
			   	if(et_dis_amt.length() == 0){
			    		et_dis_amt.setText("0");
			   	}
		
		   		totalDiscount=((Double.parseDouble(et_dis_amt.getText().toString())) + 0.00 );
	    	
		    	Log.v("Total (Discount % 2)", totalDiscount+"");
	    	}
	   		
    			values= (Double.parseDouble(et_price.getText().toString()) * ((double) totPieces)) - totalDiscount; 
    				
	    		if((Double.parseDouble(et_price.getText().toString())* ((double) totPieces)) < totalDiscount){
    			

	    			toast.createToastErrorMessage("Maximum Discount Amount Exceed...", getActivity());
	    			
	    			et_dis_per.setText("0.00");
		    		totalDiscount=0.00;
		    		values=0.00;
		    		casesCalc();
		    		discountpercentageCalc();

	    		
	    		}else{
	    			setValues(String.format("%,.2f",values),String.format("%,.2f",totalDiscount));
	    		}	
    	//	}else{
    	//		Log.v("### Testing ###", "DISCOUNT PER");
    	//	}
			
    	}	
	}

//---------------------------------------------- end -----------------------------------------------

	private void clearTextFields() {
		// TODO Auto-generated method stub
		values=0.0;
		totalDiscount=0.0;
		index_id=0;
		
		totPieces=0;
		
    	et_dis_amt.setText("0.00");
		et_dis_per.setText("0.00");
		et_item.setText("");
		et_unit.setText("0");
		et_price.setText("0.00");
		et_cases.setText("0");
		et_pieces.setText("0");
		tv_value.setText("0.00");
		tv_total_discount_amt.setText("0.00");
		
		bAdd.setText("Add");
		
		if(totPieces == 0){
    		et_dis_amt.setEnabled(false);
    		et_dis_per.setEnabled(false);
    		et_cases.requestFocus();
    	}
	}
		
	ArrayList<Items> list=null;
	void prodcutDetailsDialogbox()
	{		
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.order_details_search_item);
		
		final SearchView search = (SearchView) dialog.findViewById(R.id.et_search);
		final ListView productList=(ListView) dialog.findViewById(R.id.lv_product_list); 
		
		
		dialog.setCancelable(true);
		
		final ItemsDS itemsDS =new ItemsDS(getActivity());
		final ItemPriDS priDS=new ItemPriDS(getActivity());
		productList.clearTextFilter();
		
		list= itemsDS.getAllItemForVanSale("","txntype ='22'",referenceNum.getCurrentRefNo(getResources().getString(R.string.VanNumVal)),new SalRepDS(getActivity()).getCurrentRepCode());
		productList.setAdapter(new ProductAdapter(getActivity(), list));

		productList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				selectedItem = list.get(position);
				
				String itemName=selectedItem.getFITEM_ITEM_NAME();
				String itemcode=selectedItem.getFITEM_ITEM_CODE();
				
				et_item.setText(selectedItem.getFITEM_ITEM_NAME());
				et_unit.setText(selectedItem.getFITEM_NOU_CASE());
				
				double unitPrice= Double.parseDouble(priDS.getProductPriceByCode(selectedItem.getFITEM_ITEM_CODE()))/Double.parseDouble(selectedItem.getFITEM_NOU_CASE());
				
				Log.v("unit price", unitPrice+"");
				et_price.setText(String.format("%.2f", unitPrice));
				
				toast.createToastMessage(selectedItem.getFITEM_ITEM_NAME(), getActivity());
				
				dialog.dismiss();
			}
		});
		
			
		search.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) 
			{
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) 
			{
				
				list.clear();
				list= itemsDS.getAllItemForVanSale(newText,"txntype ='22'",referenceNum.getCurrentRefNo(getResources().getString(R.string.VanNumVal)),new SalRepDS(getActivity()).getCurrentRepCode());
				productList.clearTextFilter();
				productList.setAdapter(new ProductAdapter(getActivity(), list));
				
				return false;
			}
		});				
		dialog.show();
	}
	
	
	private void setTitle(String title){
		SetTitleAdapter adapter =new SetTitleAdapter();
		adapter.createCutomActionBarTitle(title, getActivity());
	}
	
	private void setValues(String val,String totalDis){
		tv_value.setText(val);
		tv_total_discount_amt.setText(totalDis);
	}

	@Override
	public void onTaskCompleted(String result) {
		// TODO Auto-generated method stub
		try {
			if(!result.equals("") || !result.equals("No Address"))
			{
				
				MainActivity activity =(MainActivity) getActivity();
				
					if(activity.selectedInvHed.getFINVHED_ADDRESS() == null){
						toast.createToastMessage(result, getActivity());
						SharedPreferencesClass.setLocalSharedPreference(getActivity(), "GPS_Address",result);
						activity.selectedInvHed.setFINVHED_ADDRESS(result);
					}
				
			}
		}catch (Exception e){
			Log.v("Exception Selected OrdHed ", e.toString());
		}
	}
}
